using System;
using System.Collections;
using System.Reflection;
using System.Windows.Forms;
using NCql.Parser;

namespace NCql.Demo
{
    public partial class DemoForm : Form
    {
        public DemoForm()
        {
            InitializeComponent();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            buildTree(textBox1.Text);
        }


        private void buildTree(string cql)
        {
            treeView1.Nodes.Clear();

            var parser = new CqlQueryParser();


            try
            {
                CqlQuery query = parser.Parse(cql);
                addToTree(query, treeView1.Nodes);
            }
            catch (CqlParseException ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void addToTree(object obj, TreeNodeCollection nodes)
        {
            var tn = new TreeNode();
            tn.Tag = obj;
            tn.Text = obj.GetType().Name;
            nodes.Add(tn);

            if (obj is IEnumerable)
            {
                foreach (object child in ((IEnumerable) obj))
                {
                    addToTree(child, tn.Nodes);
                }
            }
            else
            {
                PropertyInfo[] properties = obj.GetType().GetProperties();
                foreach (PropertyInfo pi in properties)
                {
                    object val = pi.GetValue(obj, null);
                    if (val is ValueType)
                        continue;

                    if (val is string)
                        continue;

                    addToTree(val, tn.Nodes);
                }
            }
        }


        private void listBox1_DoubleClick(object sender, EventArgs e)
        {
            buildTree(listBox1.SelectedItem.ToString());
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node == null)
            {
                propertyGrid1.SelectedObject = null;
                return;
            }

            propertyGrid1.SelectedObject = e.Node.Tag;
        }
    }
}